<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 登录卡片 -->
      <el-card class="login-card" shadow="always">
        <template #header>
          <div class="login-header">
            <div class="logo">
              <div class="earth-icon">🌍</div>
              <h2>Easy Go 后台管理系统</h2>
            </div>
            <p class="subtitle">管理员登录</p>
          </div>
        </template>

        <!-- 登录表单 -->
        <el-form
            :model="loginForm"
            :rules="loginRules"
            ref="loginFormRef"
            size="large"
            @keyup.enter="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                prefix-icon="User"
                clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                :loading="loginLoading"
                @click="handleLogin"
                class="login-btn"
            >
              {{ loginLoading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 注册链接 -->
        <div class="login-footer">
          <span>还没有账号？</span>
          <el-link type="primary" @click="showRegister = true">立即注册</el-link>
        </div>
      </el-card>

      <!-- 注册对话框 -->
      <el-dialog
          v-model="showRegister"
          title="用户注册"
          width="400px"
          :before-close="handleRegisterClose"
      >
        <el-form
            :model="registerForm"
            :rules="registerRules"
            ref="registerFormRef"
            label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                show-password
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="showRegister = false">取消</el-button>
          <el-button
              type="primary"
              :loading="registerLoading"
              @click="handleRegister"
          >
            {{ registerLoading ? '注册中...' : '注册' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 登录表单相关
const loginFormRef = ref()
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const loginLoading = ref(false)

// 注册表单相关
const registerFormRef = ref()
const showRegister = ref(false)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

const registerLoading = ref(false)

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loginLoading.value = true

    // 调用登录接口
    await authStore.login(loginForm)

    ElMessage.success('登录成功！')
    router.push('/')
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loginLoading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    registerLoading.value = true

    // 调用注册接口
    await authStore.register(registerForm)

    ElMessage.success('注册成功！')
    showRegister.value = false
    // 清空注册表单
    Object.assign(registerForm, {
      username: '',
      password: '',
      confirmPassword: ''
    })
  } catch (error) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    registerLoading.value = false
  }
}

// 注册对话框关闭处理
const handleRegisterClose = (done) => {
  // 清空表单验证
  registerFormRef.value?.clearValidate()
  // 清空表单数据
  Object.assign(registerForm, {
    username: '',
    password: '',
    confirmPassword: ''
  })
  done()
}

onMounted(() => {
  // 初始化认证状态
  authStore.initAuth()

  // 如果已登录，跳转到首页
  if (authStore.isLoggedIn) {
    router.push('/')
  }
})
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  border: none;
  border-radius: 10px;
  overflow: hidden;
}

.login-header {
  text-align: center;
  padding: 20px 0;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 10px;
}

.earth-icon {
  font-size: 32px;
}

.logo h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  color: #666;
}

.login-footer .el-link {
  margin-left: 5px;
}

:deep(.el-dialog) {
  border-radius: 10px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
  margin: 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
}
</style>